import 'package:get/get.dart';

import 'home_state.dart';
import '../../data/models/prompt_model.dart';
import '../../data/models/tag_model.dart';
import '../../data/services/file_service.dart';
import '../../data/services/search_service.dart';
import '../../data/services/default_data_service.dart';
import '../../data/widgets/advanced_search_dialog.dart';
import '../../core/enums/app_enums.dart';

/// 主页逻辑控制器 - Home Logic Controller
/// 处理主页的所有业务逻辑
/// This class contains all business logic for the home page
/// 此类包含主页的所有业务逻辑，不定义状态变量
class HomeLogic extends GetxController {
  final HomeState state = HomeState();
  final FileService _fileService = Get.find<FileService>();

  @override
  void onInit() {
    super.onInit();
    // 加载Prompt数据 - Load prompt data
    // This method loads all prompts when the controller is initialized
    // 当控制器初始化时加载所有Prompt数据
    loadPrompts();
  }

  @override
  void onClose() {
    // 释放资源 - Dispose resources
    // Clean up text controller to prevent memory leaks
    // 清理文本控制器以防止内存泄漏
    state.searchController.dispose();
    super.onClose();
  }

  /// 加载所有 Prompt - Load all prompts
  /// Fetches all prompts from file service and updates the UI
  /// 从文件服务获取所有Prompt并更新UI
  Future<void> loadPrompts() async {
    try {
      // 设置加载状态 - Set loading state
      // Show loading indicator to user
      // 向用户显示加载指示器
      state.isLoading = true;
      update(); // GetX update method to refresh UI - GetX更新方法刷新UI

      // 调用文件服务API获取所有Prompt - Call file service API to get all prompts
      // FileService.getAllPrompts() returns Future<List<PromptModel>>
      // FileService.getAllPrompts()返回Future<List<PromptModel>>
      List<PromptModel> loadedPrompts = await _fileService.getAllPrompts();

      // 如果没有数据，加载默认数据 - Load default data if no data exists
      // This provides sample prompts for new users or empty databases
      // 为新用户或空数据库提供示例Prompt
      if (loadedPrompts.isEmpty) {
        loadedPrompts = DefaultDataService.getDefaultPrompts();
        // 保存默认数据到文件系统 - Save default data to file system
        for (final prompt in loadedPrompts) {
          try {
            await _fileService.createPrompt(
              title: prompt.title,
              content: prompt.content,
              tags: prompt.tags,
              category: prompt.category,
              description: prompt.description,
              fileFormat: prompt.fileFormat,
              metadata: prompt.metadata,
            );
          } catch (e) {
            // 忽略保存错误，继续处理其他数据 - Ignore save errors, continue with other data
            print('保存默认Prompt失败: ${prompt.title} - $e');
          }
        }
      }

      // 更新状态中的Prompt列表 - Update prompts list in state
      state.prompts = loadedPrompts;

      // 应用筛选条件 - Apply filters
      // This method filters and sorts the loaded prompts
      // 此方法对加载的Prompt进行筛选和排序
      _applyFilters();
    } catch (e) {
      // 错误处理 - Error handling
      // Show error message to user using GetX snackbar
      // 使用GetX snackbar向用户显示错误消息
      Get.snackbar('错误', '加载 Prompt 失败: $e');
    } finally {
      // 清除加载状态 - Clear loading state
      // Hide loading indicator regardless of success or failure
      // 无论成功或失败都隐藏加载指示器
      state.isLoading = false;
      update(); // Update UI to reflect state changes - 更新UI以反映状态变化
    }
  }

  /// 搜索 Prompt - Search Prompts
  /// Performs search operation based on keyword input
  /// 基于关键词输入执行搜索操作
  void searchPrompts(String keyword) {
    // 更新搜索关键词状态 - Update search keyword state
    state.searchKeyword = keyword;

    // 如果关键词为空，显示所有筛选结果 - If keyword is empty, show all filtered results
    if (keyword.isEmpty) {
      _applyFilters();
      return;
    }

    // 执行搜索 - Perform search
    // SearchService.simpleSearch() is a utility method for text search
    // SearchService.simpleSearch()是用于文本搜索的工具方法
    final results = SearchService.simpleSearch(
      state.prompts, // Source list to search in - 要搜索的源列表
      keyword, // Search term - 搜索词
      caseSensitive: false, // Case insensitive search - 不区分大小写搜索
    );

    // 更新筛选结果 - Update filtered results
    state.filteredPrompts = results;
    update(); // Refresh UI with search results - 用搜索结果刷新UI
  }

  /// 清除搜索 - Clear search
  /// Resets search keyword and shows all filtered prompts
  /// 重置搜索关键词并显示所有筛选的Prompt
  void clearSearch() {
    state.searchKeyword = '';
    _applyFilters();
  }

  /// 清除筛选条件 - Clear Filters
  /// Resets all filter conditions to default state
  /// 将所有筛选条件重置为默认状态
  void clearFilters() {
    state.selectedTags.clear();
    state.selectedCategory = '';
    state.showFavoritesOnly = false;
    _applyFilters();
    update();
  }

  /// 设置分类筛选 - Set Category Filter
  /// Filters prompts by selected category
  /// 按选定分类筛选Prompt
  void setCategoryFilter(String category) {
    state.selectedCategory = category;
    _applyFilters();
    update();
  }

  /// 切换收藏筛选 - Toggle Favorite Filter
  /// Shows only favorited prompts when enabled
  /// 启用时仅显示收藏的Prompt
  void toggleFavoriteFilter() {
    state.showFavoritesOnly = !state.showFavoritesOnly;
    _applyFilters();
    update();
  }

  /// 设置标签筛选 - Set tag filter
  /// Filters prompts by selected tags
  /// 按选定标签筛选Prompt
  void setTagFilter(List<String> tags) {
    state.selectedTags = tags;
    _applyFilters();
  }

  /// 切换标签筛选 - Toggle tag filter
  /// Adds or removes a tag from the filter list
  /// 在筛选列表中添加或移除标签
  void toggleTagFilter(String tag) {
    if (state.selectedTags.contains(tag)) {
      state.selectedTags.remove(tag);
    } else {
      state.selectedTags.add(tag);
    }
    _applyFilters();
    update();
  }

  /// 设置排序类型 - Set Sort Type
  /// Changes the sorting method for prompt list
  /// 更改Prompt列表的排序方法
  void setSortType(SortType sortType) {
    state.sortType = sortType;
    _applyFilters();
    update();
  }

  /// 切换视图模式 - Toggle view mode
  /// Switches between list and grid view
  /// 在列表视图和网格视图之间切换
  void toggleViewMode() {
    state.viewMode =
        state.viewMode == ViewMode.list ? ViewMode.grid : ViewMode.list;
    update();
  }

  /// 切换搜索栏显示 - Toggle search bar visibility
  /// Shows or hides the search bar
  /// 显示或隐藏搜索栏
  void toggleSearchBar() {
    state.showSearchBar = !state.showSearchBar;
    if (!state.showSearchBar) {
      clearSearch();
    }
    update();
  }

  /// 应用筛选 - Apply filters
  /// Internal method to filter prompts based on current filter settings
  /// 内部方法，根据当前筛选设置筛选Prompt
  void _applyFilters() {
    // 从原始列表创建副本 - Create copy from original list
    var filtered = List<PromptModel>.from(state.prompts);

    // 应用收藏筛选 - Apply favorite filter
    // PromptModel.getIsFavorite() checks metadata for favorite status
    // PromptModel.getIsFavorite()检查元数据中的收藏状态
    if (state.showFavoritesOnly) {
      filtered = filtered.where((prompt) => prompt.getIsFavorite()).toList();
    }

    // 应用分类筛选 - Apply category filter
    // Filter by category if a specific category is selected
    // 如果选择了特定分类则按分类筛选
    if (state.selectedCategory.isNotEmpty && state.selectedCategory != '全部') {
      filtered = filtered
          .where((prompt) => prompt.category == state.selectedCategory)
          .toList();
    }

    // 应用标签筛选 - Apply tag filter
    // Filter prompts that contain all selected tags
    // 筛选包含所有选定标签的Prompt
    if (state.selectedTags.isNotEmpty) {
      filtered = filtered.where((prompt) {
        return state.selectedTags.every((tag) => prompt.tags.contains(tag));
      }).toList();
    }

    // 更新筛选结果 - Update filtered results
    state.filteredPrompts = filtered;

    // 应用排序 - Apply sorting
    _applySorting();
  }

  /// 应用排序 - Apply sorting
  /// Internal method to sort filtered prompts
  /// 内部方法对筛选后的Prompt进行排序
  void _applySorting() {
    switch (state.sortType) {
      case SortType.name:
      case SortType.titleAsc:
        // 按标题升序排序 - Sort by title ascending
        state.filteredPrompts.sort((a, b) => a.title.compareTo(b.title));
        break;
      case SortType.titleDesc:
        // 按标题降序排序 - Sort by title descending
        state.filteredPrompts.sort((a, b) => b.title.compareTo(a.title));
        break;
      case SortType.dateCreated:
      case SortType.createdDesc:
        // 按创建时间降序排序 - Sort by creation time descending
        state.filteredPrompts
            .sort((a, b) => b.createdAt.compareTo(a.createdAt));
        break;
      case SortType.createdAsc:
        // 按创建时间升序排序 - Sort by creation time ascending
        state.filteredPrompts
            .sort((a, b) => a.createdAt.compareTo(b.createdAt));
        break;
      case SortType.lastUsed:
      case SortType.updatedDesc:
        // 按最后修改时间降序排序 - Sort by last modified time descending
        state.filteredPrompts
            .sort((a, b) => b.lastModified.compareTo(a.lastModified));
        break;
      case SortType.updatedAsc:
        // 按最后修改时间升序排序 - Sort by last modified time ascending
        state.filteredPrompts
            .sort((a, b) => a.lastModified.compareTo(b.lastModified));
        break;
      case SortType.sizeDesc:
        // 按内容长度降序排序 - Sort by content length descending
        state.filteredPrompts
            .sort((a, b) => b.content.length.compareTo(a.content.length));
        break;
    }
    update(); // Update UI after sorting - 排序后更新UI
  }

  /// 获取所有标签 - Get all tags
  /// Extracts unique tags from all prompts
  /// 从所有Prompt中提取唯一标签
  List<String> getAllTags() {
    final allTags = <String>{};
    for (final prompt in state.prompts) {
      allTags.addAll(prompt.tags);
    }
    return allTags.toList()..sort();
  }

  /// 获取所有分类 - Get all categories
  /// Extracts unique categories from all prompts
  /// 从所有Prompt中提取唯一分类
  List<String> getAllCategories() {
    final allCategories = <String>{};
    for (final prompt in state.prompts) {
      if (prompt.category.isNotEmpty) {
        allCategories.add(prompt.category);
      }
    }
    return allCategories.toList()..sort();
  }

  /// Extracts unique formats from all prompts
  /// 从所有Prompt中提取唯一格式
  List<String> getAllFormats() {
    final allFormats = <String>{};
    for (final prompt in state.prompts) {
      if (prompt.getFormat().isNotEmpty) {
        allFormats.add(prompt.getFormat());
      }
    }
    return allFormats.toList()..sort();
  }

  /// 切换 Prompt 收藏状态 - Toggle prompt favorite status
  /// Updates the favorite status of a specific prompt
  /// 更新特定Prompt的收藏状态
  Future<void> togglePromptFavorite(String promptId) async {
    try {
      // 查找Prompt索引 - Find prompt index
      final promptIndex = state.prompts.indexWhere((p) => p.id == promptId);
      if (promptIndex == -1) return;

      // 获取当前Prompt - Get current prompt
      final prompt = state.prompts[promptIndex];

      // 创建新的元数据副本 - Create new metadata copy
      final newMetadata = Map<String, dynamic>.from(prompt.metadata);
      newMetadata['isFavorite'] = !(prompt.metadata['isFavorite'] ?? false);

      // 创建更新后的Prompt实例 - Create updated prompt instance
      // Using constructor instead of copyWith for better compatibility
      // 使用构造函数而不是copyWith以获得更好的兼容性
      final updatedPrompt = PromptModel(
        id: prompt.id,
        title: prompt.title,
        content: prompt.content,
        tags: prompt.tags,
        category: prompt.category,
        description: prompt.description,
        createdAt: prompt.createdAt,
        lastModified: DateTime.now(),
        version: prompt.version,
        filePath: prompt.filePath,
        fileFormat: prompt.fileFormat,
        metadata: newMetadata,
        usageCount: prompt.usageCount,
        templateVariables: prompt.templateVariables,
      );

      // 更新状态中的Prompt - Update prompt in state
      state.prompts[promptIndex] = updatedPrompt;
      _applyFilters();
      update();
    } catch (e) {
      Get.snackbar('错误', '更新收藏状态失败: $e');
    }
  }

  /// 删除 Prompt - Delete prompt
  /// Removes a prompt from storage and updates the list
  /// 从存储中删除Prompt并更新列表
  Future<void> deletePrompt(String promptId) async {
    try {
      // 调用文件服务API删除Prompt - Call file service API to delete prompt
      await _fileService.deletePrompt(promptId);

      // 从状态列表中移除 - Remove from state list
      state.prompts.removeWhere((p) => p.id == promptId);
      _applyFilters();
      Get.snackbar('成功', 'Prompt 已删除');
    } catch (e) {
      Get.snackbar('错误', '删除 Prompt 失败: $e');
    }
  }

  /// 复制 Prompt - Duplicate prompt
  /// Creates a copy of an existing prompt
  /// 创建现有Prompt的副本
  Future<void> duplicatePrompt(String promptId) async {
    try {
      // 查找原始Prompt - Find original prompt
      final originalPrompt = state.prompts.firstWhere((p) => p.id == promptId);

      // 创建新的 PromptModel 实例 - Create new PromptModel instance
      // Generate unique ID using timestamp - 使用时间戳生成唯一ID
      final duplicatedPrompt = PromptModel(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        title: '${originalPrompt.title} (副本)',
        content: originalPrompt.content,
        tags: originalPrompt.tags,
        category: originalPrompt.category,
        description: originalPrompt.description,
        createdAt: DateTime.now(),
        lastModified: DateTime.now(),
        version: 1,
        filePath: originalPrompt.filePath,
        fileFormat: originalPrompt.fileFormat,
        metadata: originalPrompt.metadata,
        usageCount: 0,
        templateVariables: originalPrompt.templateVariables,
      );

      // 调用文件服务API创建新Prompt - Call file service API to create new prompt
      await _fileService.createPrompt(
        title: duplicatedPrompt.title,
        content: duplicatedPrompt.content,
        tags: duplicatedPrompt.tags,
        category: duplicatedPrompt.category,
        description: duplicatedPrompt.description,
        fileFormat: duplicatedPrompt.fileFormat,
        metadata: duplicatedPrompt.metadata,
      );

      // 添加到状态列表 - Add to state list
      state.prompts.add(duplicatedPrompt);
      _applyFilters();
      Get.snackbar('成功', 'Prompt 已复制');
    } catch (e) {
      Get.snackbar('错误', '复制 Prompt 失败: $e');
    }
  }

  /// 进入选择模式 - Enter selection mode
  /// Enables multi-selection mode for batch operations
  /// 启用多选模式进行批量操作
  void enterSelectionMode() {
    state.isSelectionMode = true;
    state.selectedPromptIds.clear();
    update();
  }

  /// 退出选择模式 - Exit selection mode
  /// Disables multi-selection mode
  /// 禁用多选模式
  void exitSelectionMode() {
    state.isSelectionMode = false;
    state.selectedPromptIds.clear();
    update();
  }

  /// 切换Prompt选择状态 - Toggle prompt selection
  /// Adds or removes prompt from selection list
  /// 在选择列表中添加或移除Prompt
  void togglePromptSelection(String promptId) {
    if (state.selectedPromptIds.contains(promptId)) {
      state.selectedPromptIds.remove(promptId);
    } else {
      state.selectedPromptIds.add(promptId);
    }
    update();
  }

  /// 全选/取消全选 - Select all / Deselect all
  /// Selects or deselects all visible prompts
  /// 选择或取消选择所有可见的Prompt
  void toggleSelectAll() {
    if (state.selectedPromptIds.length == state.filteredPrompts.length) {
      // 如果已全选，则取消全选 - If all selected, deselect all
      state.selectedPromptIds.clear();
    } else {
      // 否则全选 - Otherwise select all
      state.selectedPromptIds = state.filteredPrompts.map((p) => p.id).toList();
    }
    update();
  }

  /// 批量删除选中的Prompt - Batch delete selected prompts
  /// Deletes all selected prompts
  /// 删除所有选中的Prompt
  Future<void> deleteSelectedPrompts() async {
    try {
      for (final promptId in state.selectedPromptIds) {
        await _fileService.deletePrompt(promptId);
        state.prompts.removeWhere((p) => p.id == promptId);
      }
      exitSelectionMode();
      _applyFilters();
      Get.snackbar('成功', '已删除 ${state.selectedPromptIds.length} 个 Prompt');
    } catch (e) {
      Get.snackbar('错误', '批量删除失败: $e');
    }
  }

  /// 显示高级搜索对话框 - Show advanced search dialog
  /// Opens advanced search dialog with more filter options
  /// 打开具有更多筛选选项的高级搜索对话框
  void showAdvancedSearch() {
    Get.dialog(
      AdvancedSearchDialog(
        availableCategories: getAllCategories(),
        availableFormats: getAllFormats(),
        availableTags: getAllTags()
            .map((tag) =>
                TagModel(name: tag, id: tag, createdAt: DateTime.now()))
            .toList(),
      ),
    ).then((filters) {
      if (filters != null) {
        // 应用高级搜索筛选 - Apply advanced search filters
        // This callback receives filter parameters from the dialog
        // 此回调从对话框接收筛选参数
        _applyAdvancedFilters(filters);
      }
    });
  }

  /// 应用高级筛选 - Apply advanced filters
  /// Internal method to apply complex filter combinations
  /// 内部方法应用复杂的筛选组合
  void _applyAdvancedFilters(Map<String, dynamic> filters) {
    // Implementation for advanced filtering logic
    // 高级筛选逻辑的实现
    // This would include date ranges, content length, etc.
    // 这将包括日期范围、内容长度等
    _applyFilters();
    update();
  }

  /// 创建新Prompt - Create new prompt
  /// Navigates to prompt creation page
  /// 导航到Prompt创建页面
  void createNewPrompt() {
    // 使用GetX路由导航到编辑页面 - Use GetX routing to navigate to edit page
    Get.toNamed('/edit');
  }

  /// 编辑Prompt - Edit prompt
  /// Navigates to prompt editing page
  /// 导航到Prompt编辑页面
  void editPrompt(String promptId) {
    // 使用GetX路由导航到编辑页面，传递Prompt ID - Navigate to edit page with prompt ID
    Get.toNamed('/edit', arguments: {'promptId': promptId});
  }

  /// 查看Prompt详情 - View prompt details
  /// Navigates to prompt detail page
  /// 导航到Prompt详情页面
  void viewPromptDetail(String promptId) {
    // 使用GetX路由导航到详情页面 - Use GetX routing to navigate to detail page
    Get.toNamed('/detail', arguments: {'promptId': promptId});
  }

  /// 刷新数据 - Refresh data
  /// Reloads all prompts from storage
  /// 从存储重新加载所有Prompt
  Future<void> refreshData() async {
    await loadPrompts();
  }

  /// 设置底部导航索引 - Set bottom navigation index
  /// Updates the current tab index
  /// 更新当前标签索引
  void setTabIndex(int index) {
    state.tabIndex = index;
    update();
  }
}
